package com.atguigu.tingshu.account.receiver;

import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import org.springframework.amqp.core.Message;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
public class AccountReceiver {
    @Autowired
    private UserAccountService userAccountService;

    /**
     * 监听用户注册消息队列，处理用户注册逻辑
     * 此方法通过RabbitMQ监听特定队列中的消息，当接收到消息时，它将处理用户注册流程
     *
     * @param userId 用户ID，用于标识注册的用户
     * @param message 接收到的消息对象，包含消息的内容和其他属性
     * @param channel 消息通道，用于确认消息处理完成
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_USER_REGISTER,durable = "true",autoDelete = "false"),
    exchange = @Exchange(value = MqConst.EXCHANGE_USER),key = MqConst.ROUTING_USER_REGISTER))
    public void register(Long userId, Message message, Channel channel){
        // 打印用户注册成功的日志
        System.out.println("用户注册成功！"+userId);

        // 获取并打印消息内容
        byte[] body = message.getBody();
        System.out.println("消息内容：\t"+ new String(body).toString());

        // 尝试调用用户账户服务进行注册
        try {
            if (userId != null){
                userAccountService.register(userId);
            }
        } catch (Exception e) {
            // 打印并记录注册过程中出现的异常信息
            System.out.println(e.getMessage());
            log.error(e.getMessage());
        }

        // 确认消息处理完成，通过basicAck方法向RabbitMQ发送确认信号
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            // 如果确认消息失败，抛出运行时异常
            throw new RuntimeException(e);
        }
    }
}
